package com.zzw.service.Impl;

import com.zzw.bean.Permissions;
import com.zzw.bean.RolesPermissionsExample;
import com.zzw.bean.RolesPermissionsKey;
import com.zzw.dao.PermissionsMapper;
import com.zzw.dao.RolesPermissionsMapper;
import com.zzw.service.PermissionsService;
import com.zzw.utils.RedisUtil;
import com.zzw.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限服务实现类
 * 实现权限相关的业务逻辑
 * @author 赵志伟
 * @version 1.0
 */
@Service
public class PermissionsServiceImpl implements PermissionsService {

    @Autowired
    private PermissionsMapper permissionsMapper;

    @Autowired
    private RolesPermissionsMapper rolesPermissionsMapper;

    @Override
    public List<Permissions> selectAll() {
        return permissionsMapper.selectAllWithoutUser();
    }

    @Override
    public List<Permissions> selectAll(Integer userId) {
        return permissionsMapper.selectAll(userId);
    }

    @Override
    public List<Permissions> selectByRoleId(Integer roleId) {
        return permissionsMapper.selectPermissionByRoleId(roleId);
    }

    @Override
    public boolean insert(Permissions permission) {
        // 设置默认状态
        if (permission.getStatus() == null) {
            permission.setStatus(true);
        }

        // 设置创建和更新时间
        Date now = new Date();
        permission.setCreateTime(now);
        permission.setUpdateTime(now);

        return permissionsMapper.insertSelective(permission) > 0;
    }

    @Override
    public boolean update(Permissions permission) {
        // 设置更新时间
        permission.setUpdateTime(new Date());

        return permissionsMapper.updateByPrimaryKeySelective(permission) > 0;
    }

    @Override
    public boolean delete(Integer id) {
        return permissionsMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    @Transactional
    public boolean saveRolePermissions(Integer roleId, List<Integer> permissionIds) {
        try {
            // 先删除该角色的所有权限关联
            RolesPermissionsExample example = new RolesPermissionsExample();
            example.createCriteria().andRoleIdEqualTo(roleId);
            rolesPermissionsMapper.deleteByExample(example);

            // 重新添加权限关联
            if (permissionIds != null && !permissionIds.isEmpty()) {
                for (Integer permissionId : permissionIds) {
                    RolesPermissionsKey key = new RolesPermissionsKey();
                    key.setRoleId(roleId);
                    key.setPermissionId(permissionId);
                    rolesPermissionsMapper.insert(key);
                }
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> buildPermissionsTree() {
        // 获取当前登录用户
        Integer userId = ShiroUtils.getUserId();

        // 获取所有权限(如果用户已登录，则会标记用户已有的权限)
        List<Permissions> allPermissions = selectAll(userId);

        // 创建根节点列表
        List<Map<String, Object>> rootNodes = new ArrayList<>();

        // 按模块分组权限
        Map<String, List<Permissions>> modulePermissions = new LinkedHashMap<>();

        // 解析权限名称，按模块分组
        for (Permissions permission : allPermissions) {
            String name = permission.getName();
            String[] parts = name.split(":");

            if (parts.length > 0) {
                String module = parts[0]; // 模块名称

                // 将权限添加到相应模块
                if (!modulePermissions.containsKey(module)) {
                    modulePermissions.put(module, new ArrayList<>());
                }
                modulePermissions.get(module).add(permission);
            }
        }

        // 为每个模块创建一个树节点
        for (Map.Entry<String, List<Permissions>> entry : modulePermissions.entrySet()) {
            String module = entry.getKey();
            List<Permissions> permissions = entry.getValue();

            // 创建模块节点
            Map<String, Object> moduleNode = new HashMap<>();
            moduleNode.put("id", "module_" + module);
            moduleNode.put("text", moduleToDisplayName(module));
            moduleNode.put("state", "open"); // 默认展开

            // 创建子节点列表
            List<Map<String, Object>> childNodes = new ArrayList<>();

            // 为每个权限创建子节点
            for (Permissions permission : permissions) {
                Map<String, Object> permNode = new HashMap<>();
                permNode.put("id", permission.getId());

                // 格式化显示：操作(描述)
                String operation = permission.getName().contains(":") ?
                        permission.getName().split(":")[1] : permission.getName();
                String displayText = operationToDisplayName(operation);

                if (permission.getDescription() != null && !permission.getDescription().isEmpty()) {
                    displayText += " (" + permission.getDescription() + ")";
                }

                permNode.put("text", displayText);

                // 设置checked状态 - 如果checked为1表示用户有此权限，checked=true
                if (permission.getChecked() != null) {
                    boolean hasPermission = permission.getChecked() == 1;
                    permNode.put("checked", hasPermission);
                }

                childNodes.add(permNode);
            }

            moduleNode.put("children", childNodes);
            rootNodes.add(moduleNode);
        }

        return rootNodes;
    }

    /**
     * 将模块名转换为更友好的显示名称
     */
    private String moduleToDisplayName(String module) {
        switch (module.toLowerCase()) {
            case "user": return "用户管理";
            case "roles": return "角色管理";
            case "menu": return "菜单管理";
            case "permissions": return "权限管理";
            case "system": return "系统管理";
            default: return module;
        }
    }

    /**
     * 将操作名转换为更友好的显示名称
     */
    private String operationToDisplayName(String operation) {
        switch (operation.toLowerCase()) {
            case "view": return "查看";
            case "add": return "新增";
            case "update": return "编辑";
            case "delete": return "删除";
            case "export": return "导出";
            case "import": return "导入";
            default: return operation;
        }
    }
}
